import React, { useState, useEffect } from 'react';
import { Card, Button, Statistic, Row, Col, List, Typography, Space, Divider, Tag, Upload, message } from 'antd';
import { DownloadOutlined, EyeOutlined, SearchOutlined, UploadOutlined, InboxOutlined, CopyOutlined } from '@ant-design/icons';
import styled from '@emotion/styled';
import { 
  extractFromTikTokFile, 
  getDataStats, 
  generateDateFileName, 
  readJsonFile,
  type ExtractedData 
} from '../../utils/dataExtractor';
import tikTokData from '../../mock/hot_search/tiktokshopglobalselling-2025-10-23.json';

const { Title, Text, Paragraph } = Typography;
const { Dragger } = Upload;

/**
 * 数据提取演示页面组件
 * 展示从TikTok热搜数据中提取图片地址和内容的功能
 */
const DataExtractor: React.FC = () => {
  const [extractedData, setExtractedData] = useState<ExtractedData>({ src: [], content: [] });
  const [loading, setLoading] = useState<boolean>(false);
  const [showImages, setShowImages] = useState<boolean>(false);
  const [showContent, setShowContent] = useState<boolean>(false);
  const [uploadedData, setUploadedData] = useState<any>(null);
  const [fileName, setFileName] = useState<string>('');

  /**
   * 执行数据提取操作
   */
  const handleExtractData = async () => {
    setLoading(true);
    try {
      // 模拟异步操作
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 优先使用上传的数据，否则使用默认数据
      const sourceData = uploadedData || tikTokData;
      const data = extractFromTikTokFile(sourceData);
      setExtractedData(data);
      
      console.log('提取的数据:', data);
      message.success('数据提取成功！');
    } catch (error) {
      console.error('数据提取失败:', error);
      message.error('数据提取失败，请检查文件格式');
    } finally {
      setLoading(false);
    }
  };

  /**
   * 下载提取的数据为JSON文件（带日期）
   */
  const handleDownloadData = () => {
    if (extractedData.src.length === 0 && extractedData.content.length === 0) {
      message.warning('请先提取数据');
      return;
    }

    const dataStr = JSON.stringify(extractedData, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = generateDateFileName('hot');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    message.success(`数据已下载为 ${generateDateFileName('hot')}`);
  };

  /**
   * 处理文件上传
   */
  const handleFileUpload = async (file: File) => {
    try {
      setLoading(true);
      const jsonData = await readJsonFile(file);
      setUploadedData(jsonData);
      setFileName(file.name);
      message.success(`文件 ${file.name} 上传成功！`);
      
      // 自动提取数据
      setTimeout(() => {
        handleExtractData();
      }, 500);
      
    } catch (error) {
      message.error(`文件上传失败: ${error instanceof Error ? error.message : '未知错误'}`);
    } finally {
      setLoading(false);
    }
    
    // 阻止默认上传行为
    return false;
  };

  /**
   * 上传组件配置
   */
  const uploadProps = {
    name: 'file',
    multiple: false,
    accept: '.json',
    beforeUpload: handleFileUpload,
    showUploadList: false,
  };

  /**
   * 复制内容列表到剪贴板（用换行分隔，无序号）
   */
  const handleCopyContent = async () => {
    if (extractedData.content.length === 0) {
      message.warning('没有内容可复制');
      return;
    }

    try {
      const contentText = extractedData.content.join(',\n');
      await navigator.clipboard.writeText(contentText);
      message.success(`已复制 ${extractedData.content.length} 个内容到剪贴板`);
    } catch (error) {
      message.error('复制失败，请手动复制');
    }
  };

  /**
   * 复制图片地址列表到剪贴板（用换行分隔，无序号）
   */
  const handleCopyImages = async () => {
    if (extractedData.src.length === 0) {
      message.warning('没有图片地址可复制');
      return;
    }

    try {
      const imagesText = extractedData.src.join('\n');
      await navigator.clipboard.writeText(imagesText);
      message.success(`已复制 ${extractedData.src.length} 个图片地址到剪贴板`);
    } catch (error) {
      message.error('复制失败，请手动复制');
    }
  };

  // 获取统计信息
  const stats = getDataStats(extractedData);

  return (
    <DataExtractorContainer>
      <Title level={2}>TikTok 热搜数据提取工具</Title>
      <Paragraph>
        从 TikTok 热搜 JSON 数据中提取所有图片地址和内容信息，支持数据统计和导出功能。
      </Paragraph>

      {/* 文件上传区域 */}
      <Card title="上传 JSON 文件" style={{ marginBottom: 24 }}>
        <Dragger {...uploadProps}>
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
          <p className="ant-upload-hint">
            支持 JSON 格式文件，上传后将自动提取数据
          </p>
        </Dragger>
        {fileName && (
          <div style={{ marginTop: 16 }}>
            <Tag color="green">当前文件: {fileName}</Tag>
          </div>
        )}
      </Card>

      {/* 操作按钮区域 */}
      <ActionSection>
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<SearchOutlined />}
            loading={loading}
            onClick={handleExtractData}
          >
            {uploadedData ? '重新提取数据' : '提取默认数据'}
          </Button>
          <Button 
            icon={<DownloadOutlined />}
            disabled={extractedData.src.length === 0}
            onClick={handleDownloadData}
          >
            下载数据 ({generateDateFileName('hot')})
          </Button>
        </Space>
      </ActionSection>

      {/* 统计信息卡片 */}
      {extractedData.src.length > 0 && (
        <StatsSection>
          <Row gutter={16}>
            <Col span={6}>
              <Card>
                <Statistic
                  title="图片地址总数"
                  value={stats.totalImages}
                  valueStyle={{ color: '#3f8600' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="内容总数"
                  value={stats.totalContent}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="唯一图片地址"
                  value={stats.uniqueImages}
                  valueStyle={{ color: '#722ed1' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="唯一内容"
                  value={stats.uniqueContent}
                  valueStyle={{ color: '#eb2f96' }}
                />
              </Card>
            </Col>
          </Row>
        </StatsSection>
      )}

      {/* 数据展示区域 */}
      {extractedData.src.length > 0 && (
        <DataDisplaySection>
          <Row gutter={16}>
            {/* 图片地址列表 */}
            <Col span={12}>
              <Card 
                title={
                  <Space>
                    <span>图片地址列表</span>
                    <Tag color="green">{extractedData.src.length} 个</Tag>
                  </Space>
                }
                extra={
                  <Space>
                    <Button 
                      type="link" 
                      icon={<CopyOutlined />}
                      onClick={handleCopyImages}
                      size="small"
                    >
                      复制
                    </Button>
                    <Button 
                      type="link" 
                      icon={<EyeOutlined />}
                      onClick={() => setShowImages(!showImages)}
                      size="small"
                    >
                      {showImages ? '隐藏' : '显示'}
                    </Button>
                  </Space>
                }
              >
                {showImages && (
                  <List
                    size="small"
                    dataSource={extractedData.src.slice(0, 10)}
                    renderItem={(item) => (
                      <List.Item>
                        <Text ellipsis={{ tooltip: item }} style={{ width: '100%' }}>
                          {item}
                        </Text>
                      </List.Item>
                    )}
                    footer={
                      extractedData.src.length > 10 && (
                        <Text type="secondary">
                          显示前 10 个，共 {extractedData.src.length} 个图片地址
                        </Text>
                      )
                    }
                  />
                )}
              </Card>
            </Col>

            {/* 内容列表 */}
            <Col span={12}>
              <Card 
                title={
                  <Space>
                    <span>内容列表</span>
                    <Tag color="blue">{extractedData.content.length} 个</Tag>
                  </Space>
                }
                extra={
                  <Space>
                    <Button 
                      type="link" 
                      icon={<CopyOutlined />}
                      onClick={handleCopyContent}
                      size="small"
                    >
                      复制
                    </Button>
                    <Button 
                      type="link" 
                      icon={<EyeOutlined />}
                      onClick={() => setShowContent(!showContent)}
                      size="small"
                    >
                      {showContent ? '隐藏' : '显示'}
                    </Button>
                  </Space>
                }
              >
                {showContent && (
                  <List
                    size="small"
                    dataSource={extractedData.content.slice(0, 10)}
                    renderItem={(item) => (
                      <List.Item>
                        <Text style={{ width: '100%' }}>
                          {item}
                        </Text>
                      </List.Item>
                    )}
                    footer={
                      extractedData.content.length > 10 && (
                        <Text type="secondary">
                          显示前 10 个，共 {extractedData.content.length} 个内容
                        </Text>
                      )
                    }
                  />
                )}
              </Card>
            </Col>
          </Row>
        </DataDisplaySection>
      )}

      {/* 提取结果预览 */}
      {extractedData.src.length > 0 && (
        <ResultPreview>
          <Divider>提取结果预览</Divider>
          <Card>
            <pre style={{ fontSize: '12px', maxHeight: '200px', overflow: 'auto' }}>
              {JSON.stringify(
                {
                  src: extractedData.src.slice(0, 3),
                  content: extractedData.content.slice(0, 3)
                },
                null,
                2
              )}
            </pre>
            <Text type="secondary">
              * 仅显示前3个项目作为预览，完整数据请点击"下载数据"按钮获取
            </Text>
          </Card>
        </ResultPreview>
      )}
    </DataExtractorContainer>
  );
};

// 样式组件
const DataExtractorContainer = styled.div`
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
`;

const ActionSection = styled.div`
  margin: 24px 0;
  text-align: center;
`;

const StatsSection = styled.div`
  margin: 24px 0;
`;

const DataDisplaySection = styled.div`
  margin: 24px 0;
`;

const ResultPreview = styled.div`
  margin: 24px 0;
`;

export default DataExtractor;